package com.hhj.sharding.sphere.demo.base;

import com.hhj.sharding.sphere.demo.enums.BusinessEnum;
import com.hhj.sharding.sphere.demo.enums.BusinessEnums;
import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

/**
 * 返回结果封装对象
 *
 * @Description
 * @Author HHJ
 * @Date 2022-02-28 18:28
 */
@Data
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    private Integer code;

    /**
     * 消息
     */
    private String message;

    /**
     * 结果数据
     */
    private T data;

    /**
     * Result
     *
     * @param code
     * @param data
     * @param message
     */
    private Result(Integer code, T data, String message) {
        this.code = code;
        this.data = data;
        this.message = message;
    }

    /**
     * 判断是否成功
     *
     * @return
     */
    public boolean ifSuccess() {
        return Objects.equals(BusinessEnums.SUCCESS.getCode(), this.code);
    }

    /**
     * 判断是否失败
     *
     * @return
     */
    public boolean ifFail() {
        return !this.ifSuccess();
    }


    public static <T> Result<T> success() {
        return new Result(BusinessEnums.SUCCESS.getCode(), null, BusinessEnums.SUCCESS.getMessage());
    }

    public static <T> Result<T> success(T data) {
        return new Result(BusinessEnums.SUCCESS.getCode(), data, BusinessEnums.SUCCESS.getMessage());
    }

    public static <T> Result<T> success(T data, String message) {
        return new Result(BusinessEnums.SUCCESS.getCode(), data, message);
    }

    public static <T> Result<T> fail() {
        return fail(BusinessEnums.ERROR.getCode(), BusinessEnums.ERROR.getMessage());
    }

    public static <T> Result<T> fail(String message) {
        return fail(BusinessEnums.ERROR.getCode(), message);
    }

    public static <T> Result<T> fail(BusinessEnum businessEnum) {
        return fail(businessEnum.getCode(), businessEnum.getMessage());
    }

    public static <T> Result<T> fail(Integer code, String message) {
        return new Result(code, null, message);
    }

    public static <T> Result<T> warn() {
        return fail(BusinessEnums.WARN.getCode(), BusinessEnums.WARN.getMessage());
    }

    public static <T> Result<T> warn(String message) {
        return fail(BusinessEnums.WARN.getCode(), message);
    }
}
